﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Utilities;

namespace TemplateLibraryConnector.UI
{
    public class ThumbNailTemplate : ITemplate
    {
        
        public ThumbNailTemplate()
        {
        }

        #region ITemplate Members

        public void InstantiateIn(Control container)
        {
            var btnSingle = new LinkButton {CommandName = "Select", Visible = false};

            container.Controls.Add(btnSingle);

            var btnDouble = new LinkButton {CommandName = "Open", Visible = false};
            container.Controls.Add(btnDouble);

            var pan = new Panel();
            pan.DataBinding += FieldDataBound;
            container.Controls.Add(pan);

        }

        #endregion

        private void FieldDataBound(object sender, EventArgs e)
        {
            var pan = (Panel)sender;

            var row = (DataListItem)pan.NamingContainer;
            var item = (System.Data.DataRowView)row.DataItem;

            var imgUrl = TemplateHubController.GetThumbNail("/_layouts/15/TemplateLibraryConnector/thumbnail.ashx?", item["FileLeafRef"].ToString());
            
            string title;
            try
            {
                title = SPEncode.HtmlEncode(item["Template_x0020_title"].ToString());    
            }
            catch(Exception)
            {
                title = SPEncode.HtmlEncode(item["Title"].ToString());    
            }

            if (string.IsNullOrEmpty(title))
                title = "no title";

            var literal = new Literal
                              {
                                  Text =
                                      "<div class=\"ThumbnailHolder\"><img class=\"ThumbnailImage\" src=\"" + imgUrl +
                                      "&width=64&height=96\" /></div>" + title
                              };
            pan.Controls.Add(literal);

        }
    }
}
